import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        ListNode list1 = null;
        ListNode list2 = null;
        if(head == null || head.next == null) {
            return head;
        }
        if(head != null && head.next != null) {
            ListNode fast = new ListNode(0);
            fast.next = head;
            ListNode slow = fast;
            while(fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            fast = slow.next;
            slow.next = null;
            list1 = sortInList(head);
            list2 = sortInList(fast);
        }
        return sort(list1,list2);
    }
    public ListNode sort(ListNode list1,ListNode list2) {
        ListNode dum = new ListNode(0);
        ListNode cur = dum;
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1 != null) {
            cur.next = list1;
        }
        if(list2 != null) {
            cur.next = list2;
        }
        return dum.next;
    }
}